<template>
  <div class="my-page">
    <!-- 用户信息头部 -->
    <div class="user-header">
      <div v-if="userStore.isLogin" class="user-info">
        <van-image
          :src="userStore.userInfo.avatar || '/imgs/default-avatar.png'"
          width="60"
          height="60"
          round
        />
        <div class="user-details">
          <div class="username">{{ userStore.userInfo.nickname || '用户' }}</div>
          <div class="user-level">{{ userStore.userInfo.level || '普通会员' }}</div>
        </div>
      </div>
      <div v-else class="login-prompt" @click="goToLogin">
        <van-image
          src="/imgs/default-avatar.png"
          width="60"
          height="60"
          round
        />
        <div class="login-text">
          <div class="login-title">点击登录</div>
          <div class="login-subtitle">登录后享受更多服务</div>
        </div>
      </div>
    </div>

    <!-- 订单中心 -->
    <div class="order-center">
      <div class="center-header">
        <span>我的订单</span>
        <span class="view-all" @click="goToOrderCenter">查看全部 ></span>
      </div>
      <div class="order-tabs">
        <div class="order-tab" @click="goToOrderCenter('buyer')">
          <van-icon name="shopping-cart-o" />
          <span>我买到的</span>
          <van-badge v-if="orderStats.buyerTotal > 0" :content="orderStats.buyerTotal" />
        </div>
        <div class="order-tab" @click="goToOrderCenter('seller')">
          <van-icon name="home-o" />
          <span>我卖出的</span>
          <van-badge v-if="orderStats.sellerTotal > 0" :content="orderStats.sellerTotal" />
        </div>
      </div>
    </div>

    <!-- 功能菜单 -->
    <div class="menu-list">
      <van-cell-group>
        <van-cell 
          v-for="item in computedMenuItems" 
          :key="item.key"
          :title="item.title"
          :icon="item.icon"
          :is-link="!item.danger"
          :class="{ 'logout-cell': item.danger }"
          :disabled="item.danger && isLoggingOut"
          @click="handleMenuClick(item)"
        />
      </van-cell-group>
    </div>

    <!-- 底部导航 -->
    <tab-bar />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getUserInfo } from '@/api/user'
import { showConfirmDialog, showLoadingToast, closeToast } from 'vant'
import TabBar from '@/components/tab-bar/index.vue'

const router = useRouter()
const userStore = useUserStore()
const isLoggingOut = ref(false)

// 获取用户信息
const fetchUserInfo = async () => {
  if (!userStore.isLogin) return
  
  try {
    const userInfo = await getUserInfo()
    userStore.setUserInfo(userInfo)
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 订单统计数据
const orderStats = ref({
  buyerTotal: 0,
  sellerTotal: 0
})

// 订单状态
const orderStatus = [
  { key: 'pending', text: '待付款', icon: 'clock-o', badge: '' },
  { key: 'paid', text: '待确认', icon: 'pending-payment', badge: '' },
  { key: 'completed', text: '已完成', icon: 'passed', badge: '' },
  { key: 'cancelled', text: '已取消', icon: 'close', badge: '' }
]

// 菜单项
const menuItems = [
  { key: 'address', title: '收货地址', icon: 'location-o' },
  { key: 'coupon', title: '我的优惠券', icon: 'coupon-o' },
  { key: 'points', title: '我的积分', icon: 'gold-coin-o' },
  { key: 'points-record', title: '积分明细', icon: 'records' },
  { key: 'favorite', title: '我的收藏', icon: 'star-o' },
  { key: 'my-qrcode', title: '我的收款码', icon: 'qr' },
  { key: 'sales-stats', title: '销售统计', icon: 'chart-trending-o' },
  { key: 'flow-statistics', title: '流水统计', icon: 'balance-list-o' },
  { key: 'service', title: '联系客服', icon: 'service-o' },
  { key: 'about', title: '关于我们', icon: 'info-o' }
]

// 如果用户已登录，添加退出登录选项
const computedMenuItems = computed(() => {
  if (userStore.isLogin) {
    return [...menuItems, { key: 'logout', title: '退出登录', icon: 'log-out', danger: true }]
  }
  return menuItems
})

// 去登录
const goToLogin = () => {
  router.push('/login')
}

// 去订单中心
const goToOrderCenter = (perspective = '') => {
  router.push({
    path: '/my-order-center',
    query: perspective ? { perspective } : {}
  })
}

// 去我的订单（保持兼容性）
const goToMyOrder = (status = '') => {
  if (!userStore.isLogin) {
    goToLogin()
    return
  }
  
  router.push({
    path: '/my-order',
    query: { status }
  })
}

// 处理菜单点击
const handleMenuClick = (item) => {
  if (!userStore.isLogin) {
    goToLogin()
    return
  }
  
  switch (item.key) {
    case 'address':
      router.push('/address')
      break
    case 'coupon':
      router.push('/my-coupon')
      break
    case 'points':
      router.push('/points-record')
      break
    case 'points-record':
      router.push('/points-record')
      break
    case 'favorite':
      router.push('/favorite')
      break
    case 'my-qrcode':
      router.push('/my-qrcode')
      break
    case 'my-purchases':
      router.push('/my-purchases')
      break
    case 'payment-confirm':
      router.push('/payment-confirm')
      break
    case 'sales-stats':
      router.push('/sales-stats')
      break
    case 'flow-statistics':
      router.push('/flow-statistics')
      break
    case 'service':
      // 打开客服
      break
    case 'about':
      router.push('/about')
      break
    case 'logout':
      showConfirmDialog({
        title: '提示',
        message: '确定要退出登录吗？',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(async () => {
        if (isLoggingOut.value) return // 防止重复点击
        isLoggingOut.value = true
        
        showLoadingToast({
          message: '退出中...',
          forbidClick: true,
        })
        
        try {
          await userStore.logout()
          closeToast()
          router.push('/login')
        } catch (error) {
          closeToast()
          console.error('退出登录失败:', error)
          // 即使退出失败，也要跳转到登录页
          router.push('/login')
        } finally {
          isLoggingOut.value = false
        }
      }).catch(() => {
        // 用户取消退出
      })
      break
  }
}

// 页面加载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style lang="scss" scoped>
.my-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 50px;
}

.user-header {
  background: linear-gradient(135deg, #157658 0%, #2d8f7a 100%);
  padding: 30px 20px;
  color: #fff;
  
  .user-info {
    display: flex;
    align-items: center;
    
    .user-details {
      margin-left: 15px;
      
      .username {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 5px;
      }
      
      .user-level {
        font-size: 14px;
        opacity: 0.8;
      }
    }
  }
  
  .login-prompt {
    display: flex;
    align-items: center;
    cursor: pointer;
    
    .login-text {
      margin-left: 15px;
      
      .login-title {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 5px;
      }
      
      .login-subtitle {
        font-size: 14px;
        opacity: 0.8;
      }
    }
  }
}

.order-center {
  background: #fff;
  margin: 10px;
  border-radius: 8px;
  padding: 15px;
  
  .center-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    font-size: 16px;
    font-weight: bold;
    
    .view-all {
      font-size: 14px;
      color: #1989fa;
      font-weight: normal;
      cursor: pointer;
    }
  }
  
  .order-tabs {
    display: flex;
    gap: 10px;
    
    .order-tab {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 15px 10px;
      background: #f8f9fa;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s ease;
      position: relative;
      
      &:hover {
        background: #e9ecef;
      }
      
      .van-icon {
        font-size: 24px;
        margin-bottom: 8px;
        color: #666;
      }
      
      span {
        font-size: 14px;
        color: #333;
        font-weight: 500;
      }
      
      .van-badge {
        position: absolute;
        top: 8px;
        right: 8px;
      }
    }
  }
}

.order-status {
  background: #fff;
  margin: 10px;
  border-radius: 8px;
  padding: 15px 0;
  
  .status-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 15px 15px;
    font-size: 16px;
    font-weight: bold;
    
    .view-all {
      font-size: 14px;
      color: #999;
      font-weight: normal;
    }
  }
  
  :deep(.van-grid-item__content) {
    padding: 10px 8px;
  }
  
  :deep(.van-grid-item__icon) {
    font-size: 24px;
    color: #157658;
  }
  
  :deep(.van-grid-item__text) {
    font-size: 12px;
    color: #333;
    margin-top: 5px;
  }
}

.menu-list {
  margin: 10px;
  
  :deep(.van-cell) {
    padding: 15px;
    
    .van-cell__title {
      font-size: 16px;
    }
    
    .van-cell__left-icon {
      font-size: 20px;
      color: #157658;
      margin-right: 10px;
    }
  }

  .logout-cell {
    color: #f00; /* 退出登录按钮的文字颜色 */
    font-weight: bold; /* 退出登录按钮的文字加粗 */
    
    &.van-cell--disabled {
      color: #ccc; /* 禁用状态下的颜色 */
      cursor: not-allowed;
    }
  }
}
</style> 